#include "biounit.h"
#include <math.h>

BioUnit::BioUnit()
{
}

BioUnit::BioUnit(float ix, float iy, unsigned short agres, unsigned short metab, unsigned short inv, unsigned short Green,
            unsigned short isearch) : x(ix), y(iy), agressive(agres),metabolism(metab),invisible(inv),green(Green),search(isearch)
{
    logic = new Logic(this);
    this->Vx = 0;
    this->Vy = 0;
    biomass = 100;
    size = 20;
    visibleList = new QList<BioUnit*>();
}

BioUnit::BioUnit(BioUnit* unit) :   x(unit->x), y(unit->y), agressive(unit->agressive), metabolism(unit->metabolism),
            invisible(unit->invisible), green(unit->green), search(unit->search)
{
    biomass = unit->biomass = unit->biomass/2.0;
    logic = new Logic(this);
    this->Vx = 0;
    this->Vy = 0;
    size = 20;
    x += size - rand()%(2*size);
    y += size - rand()%(2*size);
    visibleList = new QList<BioUnit*>();
}

void BioUnit::DoThink()
{
    logic->Think();
}

void BioUnit::DoThink(double lasttime)
{
    if(currentTask != 0)
    {
        float vx = currentTask->x - x;
        float vy = currentTask->y - y;
        double speed = this->search/3.0 + 0.5;
        switch(currentTask->mode)
        {
            case Task::GoTo:
                if (fabs(vx) <= 5 && fabs(vy) <= 5)
                {
                    Vx = 0; Vy = 0;
                    delete(currentTask);
                    currentTask=0;
                    return;
                }
                if (fabs(vy) <= 1 && fabs(vx) > 1)
                {
                    Vx = speed * (fabs(vx) / vx); Vy =  0;
                }
                if (fabs(vy) > 1 && fabs(vx) <= 1)
                {
                    Vx = 0; Vy = speed * (fabs(vy) / vy);
                }
                if (fabs(vy) > 1 && fabs(vx) > 1)
                {
                    if (fabs(vx) < fabs(vy))
                    {
                        Vx = (speed / fabs(vy)) * vx; Vy = (speed / fabs(vy)) * vy;
                    }
                    else
                    {
                        Vx = (speed / fabs(vx)) * vx; Vy = (speed / fabs(vx)) * vy;
                    }
                }
                break;
            case Task::Stop:
                if(currentTask->startTime.secsTo(QTime::currentTime()) < 5)
                {
                    Vx = 0; Vy = 0;
                }
                else
                {
                    Vx = 0; Vy = 0;
                    delete(currentTask);
                    currentTask=0;
                }
            break;
        }
    }
    logic->Think();
}

Task::Task(Mode _mode,float ix, float iy)
{
    startTime = QTime::currentTime();
    mode=_mode;
    x=ix;
    y=iy;
}
